//
//  WBPhotoViewController.swift
//  XLWibo-Swift
//
//  Created by 王林 on 2016/11/22.
//  Copyright © 2016年 木木. All rights reserved.
//

import UIKit


private let reuseIdentifier = "Cell"

let cellCount = 3

class WBPhotoViewController: UICollectionViewController {

    lazy var imageARR:[UIImage] = [UIImage]()
    override func viewDidLoad() {
        super.viewDidLoad()

        self.collectionView!.register(WBPhotoViewCell.self, forCellWithReuseIdentifier: reuseIdentifier)


    }
    

    override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        
//        var detal = imageARR.count == cellCount ? 0 : 1
        if imageARR.count == cellCount {
            return   imageARR.count + 0
        }else{
            return imageARR.count + 1
        }
//        return imageARR.count + detal
    }

    override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: reuseIdentifier, for: indexPath) as! WBPhotoViewCell
    
        // Configure the cell
        cell.backgroundColor = randomColor()
        
        cell.delegate = self
        //判断如果是最后一个就特殊处理
        if indexPath.item == imageARR.count {
            cell.cellImage = nil
        }else{
            
            cell.cellImage = imageARR[indexPath.row]
        }
        
        return cell
    }

}
//MARK:
// MARK: - 遵守协议  实现协议方法
extension WBPhotoViewController:WBPhotoViewCellDelegate{
    internal func clickAddBtn(cell: WBPhotoViewCell?) {
        //添加图片
        print("添加图片")
        //图片选择控制器
        let picker = UIImagePickerController()
        //设置picket代理
        picker.delegate = self
        //model
        self.present(picker, animated: true, completion: nil)
    }
    
    internal func clickDeleteBtn(cell: WBPhotoViewCell?) {
        //删除图片
        print("删除图片")
        guard  let indexPath = collectionView?.indexPath(for: cell!)  else {
            return
        }
      self.imageARR.remove(at: indexPath.row)
        //刷新
        self.collectionView?.reloadData()
          self.collectionView?.isHidden = self.imageARR.count == 0
    }
    
}

//MARK:
// MARK: - 遵守UIImagePickerControllerDelegate
extension WBPhotoViewController:UIImagePickerControllerDelegate,UINavigationControllerDelegate{
    //一旦调用这个方法,图片界面需要自己手动dismiss
    func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
        //获取图片
        let img = info[UIImagePickerControllerOriginalImage]  as! UIImage
        //添加
        imageARR.append(img.scaleImage(width: USC_width))
        
        
        self.collectionView?.reloadData()
        
        dismiss(animated: true, completion: {
            
        })
    }
    
}



//MARK:
// MARK: - 制定协议
@objc protocol WBPhotoViewCellDelegate :NSObjectProtocol{
    @objc optional func clickAddBtn(cell:WBPhotoViewCell?)
    @objc optional func clickDeleteBtn(cell:WBPhotoViewCell?)
    
}

//MARK:
// MARK: -- collectionViewCell
class WBPhotoViewCell: UICollectionViewCell {
    //注意 修饰词
    weak var delegate:WBPhotoViewCellDelegate?
    
    var cellImage : UIImage?{
        didSet{
            addButton.setImage(cellImage, for: .normal)
            deleteBtn.isHidden = cellImage == nil
        }
    }
    
    
    lazy var addButton :UIButton = {
        let btn = UIButton()
        btn.setBackgroundImage(#imageLiteral(resourceName: "compose_pic_add"), for: .normal)
        btn.setBackgroundImage(#imageLiteral(resourceName: "compose_pic_add_highlighted"), for: .selected)
        
        btn.addTarget(self, action: #selector(clickAdd(cell:)), for: .touchUpInside)
        return btn
    }()
    
    lazy var deleteBtn: UIButton = {
        let btn = UIButton()
        btn.setBackgroundImage(#imageLiteral(resourceName: "compose_photo_close"), for: .normal)
        
        btn.addTarget(self, action: #selector(clickDelete(cell:)), for: .touchUpInside)
        return btn
    }()
    
  @objc private func clickAdd(cell:WBPhotoViewCell){
    if cellImage != nil {

        return
    }
        delegate!.clickAddBtn?(cell: self)
  
    }
 @objc  private func clickDelete(cell:WBPhotoViewCell){
        delegate?.clickDeleteBtn?(cell: self)
    }
    
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        setupUI()
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    func setupUI(){
        self.addSubview(addButton)
        self.addSubview(deleteBtn)
        
        addButton.snp.makeConstraints { (make) in
            make.edges.equalTo(self)
        }
        deleteBtn.snp.makeConstraints { (make) in
            make.top.trailing.equalTo(self)
        }
        
    }
    
    
    
}




